<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="listQuery" :model="listQuery" inline>
                <el-form-item label="打捆时间" prop="filterTime">
                    <el-date-picker size="small" clearable @change="setFilterTime" v-model="listQuery.filterTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="进厂批次" prop="enterBatchCode">
                    <el-input size="small" clearable @blur="getHospitalByHospitalOrder" style="width: 150px;" class="filter-item" placeholder="请输入批次单号" v-model="listQuery.enterBatchCode">
                    </el-input>
                </el-form-item>
                <el-form-item label="所属医院" prop="hid">
                    <el-select size="small" clearable class="filter-item" style="width: 150px" placeholder="请选择所属医院" v-model="listQuery.hid">
                        <el-option v-for="item in hospitalOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="打捆编号" prop="balingCode">
                    <el-input size="small" clearable style="width: 150px;" class="filter-item" placeholder="请输入打捆编号" v-model="listQuery.balingCode">
                    </el-input>
                </el-form-item>
                <el-form-item label="品类" prop="type">
                    <el-select size="small" clearable class="filter-item" style="width: 130px" placeholder="请选择品类" v-model="listQuery.type">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select size="small" clearable class="filter-item" style="width: 130px" placeholder="请选择状态" v-model="listQuery.status">
                        <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
                    <el-button size="small" class="filter-item" type="danger" icon="el-icon" @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="height: 42px;line-height: 32px;">
            <el-button type="primary" icon="document" @click="handleDownload" :loading="downloadLoading" style="float: right;">下载报表</el-button>
        </div>
        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" stripe>
            <el-table-column align="center" label="序号" width="60px" type="index"></el-table-column>
            <el-table-column align="center" label="打捆编号" prop="balingCode"></el-table-column>
            <el-table-column align="center" label="打捆时间" prop="createTime"></el-table-column>
            <el-table-column align="center" label="进厂批次" prop="enterBatchCode"></el-table-column>
            <el-table-column align="center" label="所属医院" prop="hospitalName"></el-table-column>
            <el-table-column align="center" label="品类" prop="typeName"></el-table-column>
            <el-table-column align="center" label="数量" prop="clothesCnt"></el-table-column>
            <el-table-column align="center" label="状态" prop="statusName"></el-table-column>
            <el-table-column align="center" label="打捆录入" prop="createUserName"></el-table-column>
            <el-table-column align="center" label="打捆详情" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="success" size="small" @click="handleShowDetail(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
            <el-table-column align="center" label="打印" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="success" size="small" @click="print(scope.row)">打印小票</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[20,50,100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next" :total="total">
            </el-pagination>
        </div>

        <el-dialog title="查看详情" center :visible.sync="dialogDetail" @close="dialogDetail=false">
            <detail :id="detailId"></detail>
        </el-dialog>

        <el-dialog title="打印小票" center :visible.sync="dialogPrint" @close="dialogPrint=false">
            <print :data="printData"></print>
        </el-dialog>
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import detail from '@/views/pack/detail'
  import print from '@/components/PrintTicket/print'
  import { parseTime, formatSearchTime } from '@/utils'
  import exportExcel from '@/components/Excel/exportExcel'
  import { fetchFactoryBalingList, fetchFactoryBaling } from '@/api/factory'
  import { fetchHospitalList, fetchHospitalBatchOrder } from '@/api/hospital'

  export default {
    name: 'PackList',
    data() {
      return {
        tableKey: 0,
        list: [],
        total: null,
        listLoading: false,
        downloadLoading: false,
        listQuery: {
          page: 1,
          size: 20,
          hid: '',
          enterBatchCode: '',
          type: '',
          balingCode: '',
          status: '',
          startTime: '',
          endTime: '',
          filterTime: []
        },
        hospitalOptions: [],
        categoryOptions: [{ name: '布草', id: 1 }, { name: '工作服', id: 2 }, { name: '手术服', id: 3 }, { name: '传染服', id: 4 }],
        statusOptions: [{ name: '待下单', id: 1 }, { name: '已下单', id: 2 }],
        dialogDetail: false,
        dialogPrint: false,
        printData: {},
        detailId: ''
      }
    },
    components: {
      exportExcel,
      detail,
      print
    },
    computed: {
      ...mapGetters([
        'fid'
      ])
    },
    created: function() {
      this.getHospital()
      this.getList()
    },
    filters: {
      parseTime
    },
    methods: {
      getHospital() {
        fetchHospitalList({ page: 1, size: 500, fid: this.fid }).then(response => {
          this.hospitalOptions = response.data && response.data.list || []
        })
      },
      getList() {
        this.listLoading = true
        var query = {
          page: this.listQuery.page,
          size: this.listQuery.size,
          hid: this.listQuery.hid,
          type: this.listQuery.type,
          status: this.listQuery.status,
          balingCode: this.listQuery.balingCode,
          enterBatchCode: this.listQuery.enterBatchCode,
          startTime: this.listQuery.startTime ? formatSearchTime(this.listQuery.startTime + ' ', true) : '',
          endTime: this.listQuery.endTime ? formatSearchTime(this.listQuery.endTime + ' ') : ''
        }
        fetchFactoryBalingList(query).then(response => {
          this.list = response.data.list || []
          this.total = Number.parseInt(response.data.count)
          this.listLoading = false
        }).catch(e => {
          this.listLoading = false
        })
      },
      setFilterTime() {
        if (this.listQuery.filterTime && this.listQuery.filterTime.length) {
          this.listQuery.startTime = this.listQuery.filterTime[0]
          this.listQuery.endTime = this.listQuery.filterTime[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetFilter() {
        this.$refs['listQuery'].resetFields()
        this.setFilterTime()
      },
      getHospitalByHospitalOrder() {
        if (!this.listQuery.enterBatchCode) return
        fetchHospitalBatchOrder({ code: this.listQuery.enterBatchCode }).then(response => {
          this.listQuery.hid = response.data && response.data.hid || ''
        })
      },
      handleShowDetail(row) {
        this.detailId = row.id
        this.dialogDetail = true
      },
      print(row) {
        fetchFactoryBaling({ id: row.id }).then(response => {
          this.printData = response.data || {}
          this.dialogPrint = true
        })
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDownload() {
        this.downloadLoading = true
        var query = {
          page: 1,
          size: 1000,
          hid: this.listQuery.hid,
          type: this.listQuery.type,
          status: this.listQuery.status,
          balingCode: this.listQuery.balingCode,
          enterBatchCode: this.listQuery.enterBatchCode,
          startTime: this.listQuery.startTime ? formatSearchTime(this.listQuery.startTime + ' ', true) : '',
          endTime: this.listQuery.endTime ? formatSearchTime(this.listQuery.endTime + ' ') : ''
        }
        fetchFactoryBalingList(query).then(response => {
          var excelList = response.data && response.data.list || []
          if (!excelList || !excelList.length) {
            this.$message({ message: '没有可下载的报表', type: 'error', showClose: true })
            this.downloadLoading = false
            return
          }
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['打捆编号', '打捆时间', '进厂批次', '所属医院', '品类', '数量', '状态', '打捆录入']
            const filterVal = ['balingCode', 'createTime', 'enterBatchCode', 'hospitalName', 'typeName', 'clothesCnt', 'statusName', 'createUserName']
            const data = this.formatJson(filterVal, excelList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '打捆列表' + parseTime(query.startTime, '{y}-{m}-{d}') + '至' + parseTime(query.endTime, '{y}-{m}-{d}'),
              autoWidth: true
            })
            this.downloadLoading = false
          })
        }).catch(e => {
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'createTime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>

<style scoped>
    .el-range-editor.el-input__inner {
        width: 273px;
        padding: 3px;
    }
</style>

